const httpProxy = require('http-proxy');

// 新建一个代理 Proxy Server 对象  
const proxy = httpProxy.createProxyServer({
    ws: true,
});

// 捕获异常  
proxy.on('error', function (err, req, res) {
    console.log(err);


    res.writeHead(500, {
        'Content-Type': 'text/plain'
    });
    res.end('Something went wrong. And we are reporting a custom error message.');
});

// 在每次请求中，调用 proxy.web(req, res config) 方法进行请求分发  
const server = require('http').createServer(function (req, res) {
    // 在这里可以自定义你的路由分发
    const host = req.headers.host;
    const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

    console.log("client ip:" + ip + ", host:" + host);

    switch (host) {
        case 'fraud.fintech.com':
        case 'fraud.xwfintech.com':
        case 'yangquan.fraud.fintech.com':
        case 'yangquan.fraud.xwfintech.com':
        case 'xw.xwfintech.com':
            proxy.web(req, res, {target: 'http://localhost:3000'});
            break;
        case 'wx.xwfintech.com':
        case 'test-wx.xwfintech.com':
            proxy.web(req, res, {target: 'http://localhost:3001'});
            break;
        case 'login.fintech.com':
            proxy.web(req, res, {target: 'http://192.168.1.154:3001'});
            break;
        case 'user.fintech.com':
            proxy.web(req, res, {target: 'http://192.168.1.154:3002'});
            break;
        default:
            res.writeHead(200, {
                'Content-Type': 'text/plain'
            });
            res.end('Welcome to my server!');
    }
});

console.log("listening on port 80");

server.listen(80);
